import { triplitClient } from "@main/triplit/client";
import type {
  CreateMcpServerData,
  McpServer,
  UpdateMcpServerData,
} from "@shared/triplit/types";
import { injectable } from "inversify";
import { BaseDbService } from "./base-db-service";

@injectable()
export class McpServerDbService extends BaseDbService {
  constructor() {
    super("mcpServers");
  }

  async insertMcpServer(data: CreateMcpServerData): Promise<McpServer> {
    return await triplitClient.insert("mcpServers", {
      ...data,
      enabled: data.enabled ?? true,
      order: data.order ?? 0,
    });
  }

  async updateMcpServer(
    serverId: string,
    updateData: UpdateMcpServerData,
  ): Promise<void> {
    await triplitClient.update("mcpServers", serverId, async (server) => {
      Object.assign(server, updateData, {
        updatedAt: new Date(),
      });
    });
  }

  async deleteMcpServer(serverId: string): Promise<void> {
    await triplitClient.delete("mcpServers", serverId);
  }

  async getMcpServerById(serverId: string): Promise<McpServer | null> {
    return await triplitClient.fetchById("mcpServers", serverId);
  }

  async enableMcpServer(serverId: string, enabled: boolean): Promise<void> {
    await this.updateMcpServer(serverId, { enabled });
  }

  async updateMcpServerOrder(serverId: string, order: number): Promise<void> {
    await this.updateMcpServer(serverId, { order });
  }

  async getMcpServersByType(
    type: "stdio" | "sse" | "streamableHTTP",
  ): Promise<McpServer[]> {
    const query = triplitClient
      .query("mcpServers")
      .Where("type", "=", type)
      .Order("order", "ASC");

    return await triplitClient.fetch(query);
  }

  async getEnabledMcpServers(): Promise<McpServer[]> {
    const query = triplitClient
      .query("mcpServers")
      .Where("enabled", "=", true)
      .Order("order", "ASC");

    return await triplitClient.fetch(query);
  }
}
